package com.xiaofeng.pochi.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaofeng.pochi.common.Result;
import com.xiaofeng.pochi.enums.StateEnums;
import com.xiaofeng.pochi.mapper.ShopProductMapper;
import com.xiaofeng.pochi.mapper.ShopUserAddressMapper;
import com.xiaofeng.pochi.pojo.LoginUser;
import com.xiaofeng.pochi.pojo.ShopProduct;
import com.xiaofeng.pochi.pojo.ShopUserAddress;
import com.xiaofeng.pochi.service.ShopUserAddressService;
import com.xiaofeng.pochi.utils.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * Created with IntelliJ IDEA
 *
 * @Author: chc
 * @Date: 2022/09/14/21:20
 * @Description:
 */
@Service
public class ShopUserAddressServiceImpl implements ShopUserAddressService {

    @Autowired
    private ShopUserAddressMapper shopUserAddressMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(ShopUserAddress shopUserAddress) {
        //处理默认收获地址
        Integer defaultStatus = shopUserAddress.getDefaultStatus();
        LoginUser loginUser = ShiroUtils.getLoginUser();
        if(StateEnums.ADDRESS_DEFAULT.getCode().equals(defaultStatus)) {
            // 当前地址是默认的收货地址，将该用户其他的地址全部修改为非默认
            shopUserAddressMapper.updateNotDefaultByUserId(loginUser.getId());
        }
        shopUserAddress.setUserId(loginUser.getId());
        shopUserAddressMapper.save(shopUserAddress);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ShopUserAddress shopUserAddress) {
        Integer defaultStatus = shopUserAddress.getDefaultStatus();
        LoginUser loginUser = ShiroUtils.getLoginUser();
        if(StateEnums.ADDRESS_DEFAULT.getCode().equals(defaultStatus)) {
            // 当前地址是默认的收货地址，将该用户其他的地址全部修改为非默认
            shopUserAddressMapper.updateNotDefaultByUserId(loginUser.getId());
        }
        shopUserAddressMapper.update(shopUserAddress);
    }

    @Override
    public void delete(Long id) {
        shopUserAddressMapper.delete(id);
    }

    @Override
    public ShopUserAddress get(Long id) {
        return shopUserAddressMapper.get(id);
    }

    @Override
    public List<ShopUserAddress> getUserAddress() {
        Long userId = ShiroUtils.getLoginUser().getId();
        return shopUserAddressMapper.getByUserId(userId);
    }
}
